package com.fbt.transfer.app.driver.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.model.LatLng;
import com.baidu.navisdk.adapter.*;
import com.baidu.navisdk.adapter.struct.BNRoutePlanInfos;
import com.baidu.navisdk.comapi.setting.SettingParams;
import com.fbt.transfer.app.driver.R;
import com.fbt.transfer.app.driver.baidu.BaiDuLocationUtil;
import com.fbt.transfer.app.driver.baidu.NaviGuideFragment;
import com.fbt.transfer.app.driver.baidu.RouteResultFragment;
import com.fbt.transfer.app.driver.databinding.ActivityOrderDetailBinding;
import com.fbt.transfer.app.driver.model.OrderStatusEnum;
import com.fbt.transfer.app.driver.model.PositionVo;
import com.fbt.transfer.app.driver.model.index.OrderUnitVo;
import com.fbt.transfer.app.driver.view.SlideToView;
import java.util.ArrayList;
import java.util.List;

/** 订单详情页面 */
public class OrderDetailActivity extends FragmentActivity
    implements RouteResultFragment.RouteInfoListener,
        NaviGuideFragment.OnNavigationCompleteListener {

  private static final String EXTRA_ORDER_KEY = "orderInfo";
  private TextView tvBookTime = null;
  private TextView tvStartAddress = null;
  private TextView tvEndAddress = null;
  private OrderUnitVo orderInfo = null;
  private ActivityOrderDetailBinding activityOrderDetailBinding = null;
  // 当前位置
  private LatLng currentLocation = null;
  // 路线信息相关控件
  private LinearLayout routeInfoLayout = null;
  private TextView tvRouteTime = null;
  private TextView tvRouteDistance = null;
  private TextView tvRouteLights = null;
  private BaiduMap baiduMap = null;

  public static void start(Context context, OrderUnitVo order) {
    Intent intent = new Intent(context, OrderDetailActivity.class);
    intent.putExtra(EXTRA_ORDER_KEY, order);
    context.startActivity(intent);
  }

  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    activityOrderDetailBinding = ActivityOrderDetailBinding.inflate(getLayoutInflater());
    setContentView(activityOrderDetailBinding.getRoot());
    orderInfo = (OrderUnitVo) getIntent().getSerializableExtra(EXTRA_ORDER_KEY);
    tvBookTime = activityOrderDetailBinding.tvBookTime;
    tvStartAddress = activityOrderDetailBinding.tvStartAddress;
    tvEndAddress = activityOrderDetailBinding.tvEndAddress;
    // 初始化路线信息相关控件
    routeInfoLayout = activityOrderDetailBinding.routeInfoLayout;
    tvRouteTime = activityOrderDetailBinding.tvRouteTime;
    tvRouteDistance = activityOrderDetailBinding.tvRouteDistance;
    tvRouteLights = activityOrderDetailBinding.tvRouteLights;
    BaiDuLocationUtil.getInstance().startLocation(false);
    // 获取当前位置
    if (BaiDuLocationUtil.locations != null) {
      currentLocation =
          new LatLng(
              BaiDuLocationUtil.locations.getLatitude(),
              BaiDuLocationUtil.locations.getLongitude());
    }
    tvStartAddress.setText(orderInfo.getStartPosition().getDetail());
    tvEndAddress.setText(orderInfo.getEndPosition().getDetail());
    tvBookTime.setText(orderInfo.getBookTime());
    OrderStatusEnum orderStatus = OrderStatusEnum.getByValue(orderInfo.getStatus());
    if (orderStatus == OrderStatusEnum.WAIT_FOR_ASSIGN) {
      activityOrderDetailBinding.slideToNavigate.setText("立即抢单");
    } else if (orderStatus == OrderStatusEnum.TAKE_ORDER
        || orderStatus == OrderStatusEnum.CHANGE_OTHER_DRIVER) {
      activityOrderDetailBinding.slideToNavigate.setText("出发接乘客");
    } else if (orderStatus == OrderStatusEnum.GO_TO_START) {
      activityOrderDetailBinding.slideToNavigate.setText("到达乘客上车点");
    } else if (orderStatus == OrderStatusEnum.WAIT_FOR_PASSENGER) {
      activityOrderDetailBinding.slideToNavigate.setText("等待乘客上车");
    } else if (orderStatus == OrderStatusEnum.ON_CAR) {
      activityOrderDetailBinding.slideToNavigate.setText("结束订单");
    } else if (orderStatus == OrderStatusEnum.FINISHED
        || orderStatus == OrderStatusEnum.COMMENTED) {
      activityOrderDetailBinding.slideToNavigate.setText("订单已结束");
    }
    activityOrderDetailBinding.slideToNavigate.setOnSlideCompleteListener(
        () -> {
          orderInfo.setStatus(OrderStatusEnum.GO_TO_START.getValue());
          toggleOrderStatus(orderStatus);
          activityOrderDetailBinding.slideToNavigate.reset();
        });

    // Add new event listeners
    activityOrderDetailBinding.slideToNavigate.setOnSlideStartListener(
        () -> {
          // Handle slide start
          Log.d("OrderDetailActivity", "Slide started");
        });

    activityOrderDetailBinding.slideToNavigate.setOnSlideProgressListener(
        progress -> {
          // Handle slide progress
          Log.d("OrderDetailActivity", "Slide progress: " + (progress * 100) + "%");
        });
    initMapView();
    routePlan();
  }

  private void initMapView() {
    View map = BaiduNaviManagerFactory.getMapManager().getMapView();
    if (map != null && map.getParent() != null) {
      ((ViewGroup) map.getParent()).removeView(map);
    }
    BaiduNaviManagerFactory.getMapManager().attach(activityOrderDetailBinding.mapContainer);
    baiduMap = BaiduNaviManagerFactory.getMapManager().getMapView().getMap();
  }

  private void routePlan() {
    OrderStatusEnum orderStatus = OrderStatusEnum.getByValue(orderInfo.getStatus());
    toggleOrderStatus(orderStatus);
  }

  private void toggleOrderStatus(OrderStatusEnum orderStatus) {
    BaiduNaviManagerFactory.getBaiduNaviManager().startLocationMonitor();
    List<BNRoutePlanNode> list = new ArrayList<>();
    PositionVo startPosition = orderInfo.getStartPosition();
    PositionVo endPosition = orderInfo.getEndPosition();
    if (orderStatus == OrderStatusEnum.GO_TO_START) {
      list.add(
          new BNRoutePlanNode.Builder()
              .latitude(BaiDuLocationUtil.locations.getLatitude())
              .longitude(BaiDuLocationUtil.locations.getLongitude())
              .name("当前位置")
              .build());
      list.add(
          new BNRoutePlanNode.Builder()
              .latitude(startPosition.getLatitude())
              .longitude(startPosition.getLongitude())
              .name(startPosition.getDetail())
              .build());
    } else if (orderStatus == OrderStatusEnum.WAIT_FOR_PASSENGER
        || orderStatus == OrderStatusEnum.ON_CAR) {

      // 停止导航
      // BaiduNaviManagerFactory.getRouteGuideManager().stopNavi();
      list.add(
          new BNRoutePlanNode.Builder()
              .latitude(BaiDuLocationUtil.locations.getLatitude())
              .longitude(BaiDuLocationUtil.locations.getLongitude())
              .name("当前位置")
              .build());
      list.add(
          new BNRoutePlanNode.Builder()
              .latitude(endPosition.getLatitude())
              .longitude(endPosition.getLongitude())
              .name(endPosition.getDetail())
              .build());
    } else {
      list.add(
          new BNRoutePlanNode.Builder()
              .latitude(startPosition.getLatitude())
              .longitude(startPosition.getLongitude())
              .name(startPosition.getDetail())
              .build());
      list.add(
          new BNRoutePlanNode.Builder()
              .latitude(endPosition.getLatitude())
              .longitude(endPosition.getLongitude())
              .name(endPosition.getDetail())
              .build());
    }
    BaiduNaviManagerFactory.getCommonSettingManager().setMultiRouteEnable(true);
    Bundle bundle = new Bundle();
    bundle.putInt(BNaviCommonParams.RoutePlanKey.VEHICLE_TYPE, IBNRoutePlanManager.Vehicle.CAR);
    BaiduNaviManagerFactory.getRoutePlanManager()
        .routePlan(
            list,
            IBNRoutePlanManager.RoutePlanPreference.ROUTE_PLAN_PREFERENCE_DEFAULT,
            bundle,
            handler);
  }

  @Override
  public void onRouteInfoCalculated(int timeMinutes, int distanceKm, int trafficLights) {
    // 显示路线信息布局
    routeInfoLayout.setVisibility(View.VISIBLE);

    // 设置路线信息文本
    tvRouteTime.setText("预计用时: " + timeMinutes + "分钟");
    tvRouteDistance.setText("距离: " + distanceKm + "公里");
    tvRouteLights.setText("红绿灯: " + trafficLights + "个");
  }  private final Handler handler =
      new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
          super.handleMessage(msg);
          OrderStatusEnum orderStatus = OrderStatusEnum.getByValue(orderInfo.getStatus());
          switch (msg.what) {
            case IBNRoutePlanManager.MSG_NAVI_ROUTE_PLAN_START:
              // 躲避限行消息
              Bundle infoBundle = (Bundle) msg.obj;
              if (infoBundle != null) {
                String info =
                    infoBundle.getString(BNaviCommonParams.BNRouteInfoKey.TRAFFIC_LIMIT_INFO);
                Log.e("OnSdkDemo", "info = " + info);
              }
              BNRoutePlanInfos routePlanInfo =
                  BaiduNaviManagerFactory.getRoutePlanManager().getRoutePlanInfo();
              break;
            case IBNRoutePlanManager.MSG_NAVI_ROUTE_PLAN_SUCCESS:
              // 算路成功
              if (orderStatus == OrderStatusEnum.TAKE_ORDER
                  || orderStatus == OrderStatusEnum.WAIT_FOR_ASSIGN
                  || orderStatus == OrderStatusEnum.CHANGE_OTHER_DRIVER
                  || orderStatus == OrderStatusEnum.WAIT_FOR_PASSENGER) {
                /* LatLng latLng = new LatLng(
                    BaiDuLocationUtil.locations.getLatitude(), BaiDuLocationUtil.locations.getLongitude());
                BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.ic_location);
                // 创建 MarkerOptions 并设置图标
                MarkerOptions markerOptions = new MarkerOptions()
                    .position(latLng)
                    .anchor(0.5f, 0.5f)
                    .icon(bitmapDescriptor); // 在这里设置图标
                // 添加 Marker 到地图
                Marker marker = (Marker) baiduMap.addOverlay(markerOptions);
                activityOrderDetailBinding.orderInfoCard.setVisibility(View.VISIBLE);*/
                FragmentManager fm = getSupportFragmentManager();
                FragmentTransaction tx = fm.beginTransaction();
                RouteResultFragment fragment = new RouteResultFragment();
                tx.add(R.id.fragment_content, fragment, "RouteResult");
                tx.commit();
              }
              break;
            case IBNRoutePlanManager.MSG_NAVI_ROUTE_PLAN_TO_NAVI:
              if (orderStatus == OrderStatusEnum.GO_TO_START
                  || orderStatus == OrderStatusEnum.ON_CAR) {
                activityOrderDetailBinding.orderInfoCard.setVisibility(View.GONE);
                Toast.makeText(getApplicationContext(), "算路成功准备进入导航", Toast.LENGTH_SHORT).show();
                BaiduNaviManagerFactory.getProfessionalNaviSettingManager()
                    .setGuideViewMode(
                        SettingParams.MapMode.CAR_3D, IBNRoutePlanManager.Vehicle.CAR);
                BaiduNaviManagerFactory.getProfessionalNaviSettingManager()
                    .setGuideViewMode(
                        SettingParams.MapMode.CAR_3D, IBNRoutePlanManager.Vehicle.CAR);
                BaiduNaviManagerFactory.getProfessionalNaviSettingManager()
                    .setSettingButtonVisible(true);
                BaiduNaviManagerFactory.getProfessionalNaviSettingManager()
                    .setIsAutoQuitWhenArrived(true);
                BaiduNaviManagerFactory.getProfessionalNaviSettingManager()
                    .setRefreshButtonVisible(true);
                BaiduNaviManagerFactory.getProfessionalNaviSettingManager().setRoadNameEnable(true);
                BaiduNaviManagerFactory.getProfessionalNaviSettingManager().setLaneLineEnable(true);
                BaiduNaviManagerFactory.getProfessionalNaviSettingManager()
                    .setRealRoadCondition(true);
                BaiduNaviManagerFactory.getProfessionalNaviSettingManager()
                    .setStartByFullView(true);
                BaiduNaviManagerFactory.getProfessionalNaviSettingManager().setYawSoundEnable(true);
                BaiduNaviManagerFactory.getProfessionalNaviSettingManager().setHighwayEnable(true);
                BaiduNaviManagerFactory.getProfessionalNaviSettingManager()
                    .setAnalogQuitButtonVisible(true);
                BaiduNaviManagerFactory.getProfessionalNaviSettingManager()
                    .setShowMainAuxiliaryOrBridge(true);
                BaiduNaviManagerFactory.getProfessionalNaviSettingManager()
                    .setBottomMoreBtnEnable(true);
                BaiduNaviManagerFactory.getProfessionalNaviSettingManager()
                    .setZoomButtonVisible(true);
                BaiduNaviManagerFactory.getRouteResultManager().startNavi();
                FragmentManager fm = getSupportFragmentManager();
                // 启动导航界面
                FragmentTransaction tx = fm.beginTransaction();
                NaviGuideFragment fragment =
                    new NaviGuideFragment(
                        (SlideToView slideToNavigateView) -> {
                          slideToNavigateView.setText("我就要滑");
                          Toast.makeText(getApplicationContext(), "滑动完成", Toast.LENGTH_SHORT)
                              .show();
                          BaiduNaviManagerFactory.getRouteGuideManager().stopNavi();
                          // 在这里执行导航开始等操作
                          orderInfo.setStatus(OrderStatusEnum.WAIT_FOR_PASSENGER.getValue());
                          activityOrderDetailBinding.orderInfoCard.setVisibility(View.VISIBLE);
                          initMapView();
                          routePlan();
                        },
                        OrderDetailActivity
                            .this); // Pass OrderDetailActivity as the OnNavigationCompleteListener
                Bundle bundle = new Bundle();
                bundle.putSerializable("orderInfo", orderInfo);
                fragment.setArguments(bundle);
                tx.replace(R.id.fragment_content, fragment, "NaviGuide");
                tx.addToBackStack("返回");
                tx.commit();
              }
              break;
            case IBNRoutePlanManager.MSG_NAVI_ROUTE_PLAN_FAILED:
              break;
            default:
              break;
          }
        }
      };

  @Override
  protected void onResume() {
    super.onResume();
    BaiduNaviManagerFactory.getMapManager().onResume();
  }

  @Override
  protected void onPause() {
    super.onPause();
    BaiduNaviManagerFactory.getMapManager().onPause();
  }

  @Override
  protected void onDestroy() {
    BaiDuLocationUtil.getInstance().stopLocation();
    BaiduNaviManagerFactory.getBaiduNaviManager().stopLocationMonitor();
    super.onDestroy();
  }

  @Override
  public void onBackPressed() {
    super.onBackPressed();
    activityOrderDetailBinding.orderInfoCard.setVisibility(View.VISIBLE);
  }

  /**
   * 获取订单信息
   *
   * @return 当前订单信息
   */
  public OrderUnitVo getOrderInfo() {
    return orderInfo;
  }

  @Override
  public void onNavigationComplete() {
    // Update order status to WAIT_FOR_PASSENGER
    orderInfo.setStatus(OrderStatusEnum.WAIT_FOR_PASSENGER.getValue());
    // Plan the route for the next segment (e.g., to the destination)
    runOnUiThread(
        () -> {
          activityOrderDetailBinding.orderInfoCard.setVisibility(View.VISIBLE);
          routePlan();
        });
  }


}
